package com.huafv.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huafv.reggie.dto.DishDto;
import com.huafv.reggie.entity.Dish;
import com.huafv.reggie.entity.DishFlavor;
import com.huafv.reggie.mapper.DishMapper;
import com.huafv.reggie.service.DishFlavorService;
import com.huafv.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;



@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private DishFlavorService dishFlavorService;
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dto) {
        // 保存菜品基本信息
        this.save(dto);
        // 菜品Id
        Long dishId = dto.getId();
        // 保存口味到口味表
        dto.getFlavors().stream().map((e) -> {
            e.setDishId(dishId);
            return e;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(dto.getFlavors());
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        // 查询菜品基本信息
        Dish dish = this.getById(id);
        // 查询菜品口味信息
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorService.list(lambdaQueryWrapper);
        DishDto dto = new DishDto();
        BeanUtils.copyProperties(dish, dto);
        dto.setFlavors(list);
        return dto;
    }

    @Override
    public void updateWithFlavor(DishDto dto) {
        // 更新dish
        this.updateById(dto);

        // 清理菜品口味数据
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId, dto.getId());
        dishFlavorService.remove(lambdaQueryWrapper);
        // 插入菜品数据
        List<DishFlavor> flavors = dto.getFlavors();

        flavors.stream().map((e) -> {
            e.setDishId(dto.getId());
            return e;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }


}
